package com.sc.ktapplication.module.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.sc.ktapplication.R
import com.sc.ktapplication.common.base.BaseFragment
import com.sc.ktapplication.common.util.LogUtil
import com.sc.ktapplication.module.adapter.EquipmentAdapter
import com.sc.ktapplication.module.entity.Equipment
import kotlinx.android.synthetic.main.fragment_record.*

class RecordFragment : BaseFragment() {

    private var index = 1
    private var size = 20
    private lateinit var adapter : EquipmentAdapter


    private val viewModel by viewModels<RecordViewModel>()

    override fun getLayoutId(): Int {
        return R.layout.fragment_record
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView.layoutManager = LinearLayoutManager(context)
        adapter = EquipmentAdapter(R.layout.item_equipment)
        recyclerView.adapter = adapter

        adapter.setOnItemClickListener { adapter, _, position ->
            val equipment = adapter.getItem(position) as Equipment
            LogUtil.print("",equipment.code)
        }

        viewModel.equipments.observe(viewLifecycleOwner, Observer {equipments->
            if(index == 1){
                adapter.setList(equipments)
            }else{
                if(null != equipments) adapter.addData(equipments)
            }
            completeLoad(null == equipments || equipments.size < size)
        })

        getEquipments()
    }

    private fun getEquipments(){
        var params = hashMapOf<String,Any>()
        params["current"] = index
        params["size"] = size
        viewModel.getEquipments(params)
    }

    protected fun completeLoad(lastPage: Boolean) {
        refresh.isRefreshing = false
        adapter.loadMoreModule.loadMoreComplete()
        if (lastPage) {
            adapter.loadMoreModule.loadMoreEnd()
        }
    }
}
